package com.jjwxc.jwjskandriod.readActivity.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.google.android.material.tabs.TabLayout;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.LoginActivity;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.my.data.UserInfoBg;
import com.jjwxc.jwjskandriod.readActivity.ReadActivity;
import com.jjwxc.jwjskandriod.readActivity.local.ReadSettingManager;
import com.jjwxc.jwjskandriod.readActivity.utils.BrightnessUtils;
import com.jjwxc.jwjskandriod.readActivity.view.PageLoader;
import com.jjwxc.jwjskandriod.readActivity.view.PageMode;
import com.jjwxc.jwjskandriod.readActivity.view.PageStyle;

import java.util.ArrayList;
import java.util.List;

public class ReadBgDialog extends Dialog {
    private PageLoader mPageLoader;
    private Activity mActivity;

    private ReadSettingManager mSettingManager;

    private int mBrightness;
    private int mTextSize;


    private boolean isTextDefault;
    private PageMode mPageMode;
    private PageStyle mPageStyle;

    private RadioGroup rg_dialog_read_model;

    TabLayout tab_read;

    boolean isVip = false;
    SeekBar mSbBrightness;

    LinearLayout ll_bg;
    RadioButton rb_rijian;
    RadioButton rb_yejian;
    FrameLayout fl_follow_system;
    CheckBox cb_follow_system;
    ImageView iv_follow_system;

    private boolean isNightMode = false;

    // 系統屏幕亮度
    private int screenBrightness;

    public ReadBgDialog(@NonNull Activity activity, PageLoader mPageLoader) {
        super(activity);
        mActivity = activity;
        this.mPageLoader = mPageLoader;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_read_bg);

        setUpWindow();
        initData();
        initWidget();
        initClick();
    }

    //设置Dialog显示的位置
    private void setUpWindow() {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        window.setAttributes(lp);
        window.getDecorView().setBackground(null);
        window.setBackgroundDrawableResource(android.R.color.transparent);
    }

    private void initData() {
        mSettingManager = ReadSettingManager.getInstance();
        screenBrightness = BrightnessUtils.getScreenBrightness(mActivity);

        mBrightness = mSettingManager.getBrightness();

        mTextSize = mSettingManager.getTextSize();
        isTextDefault = mSettingManager.isDefaultTextSize();
        mPageMode = mSettingManager.getPageMode();
        mPageStyle = mSettingManager.getPageStyle();
        isNightMode = mSettingManager.isNightMode();
    }

    private void initWidget() {
        mSbBrightness = findViewById(R.id.read_setting_sb_brightness);
        rg_dialog_read_model = findViewById(R.id.rg_dialog_read_model);

        tab_read = findViewById(R.id.tab_read);
        ll_bg = findViewById(R.id.ll_bg);
        rb_rijian = findViewById(R.id.rb_rijian);
        rb_yejian = findViewById(R.id.rb_yejian);
        fl_follow_system = findViewById(R.id.fl_follow_system);
        cb_follow_system = findViewById(R.id.cb_follow_system);
        iv_follow_system = findViewById(R.id.iv_follow_system);

        mSbBrightness.setProgress(mBrightness);
        int pos = mSettingManager.getPageStyleBgPos();
        Integer[] drawables = {
                R.drawable.read_vip_bg_one
                , R.drawable.read_vip_bg_two
                , R.drawable.read_vip_bg_three
                , R.drawable.read_vip_bg_four
                , R.drawable.read_vip_bg_five
                , R.drawable.read_vip_bg_six
                , R.drawable.read_vip_bg_seven};
        setTabs(tab_read, getLayoutInflater(), drawables, pos);

    }

    private void initClick() {
        mSbBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 手動更改，取消跟隨
                setFollowSystem(false);

                int progress = seekBar.getProgress();
                //设置当前 Activity 的亮度
                BrightnessUtils.setBrightness(mActivity, progress);
                //存储亮度的进度条
                ReadSettingManager.getInstance().setBrightness(progress);
            }
        });
        if (isNightMode) {
            ll_bg.setBackgroundResource(R.drawable.shape_black);
            rb_yejian.setChecked(true);
        } else {
            ll_bg.setBackgroundResource(R.drawable.shape_while);
            rb_rijian.setChecked(true);
        }

        // 亮度是否跟隨系統變化
        fl_follow_system.setOnClickListener(view -> {
            if(cb_follow_system.isChecked()) {
                setFollowSystem(false);
            } else {
                // 設置默認跟隨
                setFollowSystem(true);
            }
        });

        rg_dialog_read_model.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                /*switch (checkedId) {
                    case R.id.rb_rijian:
                        isNightMode = false;
                        mPageLoader.setNightMode(isNightMode);
                        ll_bg.setBackgroundResource(R.drawable.shape_while);
                        break;

                    case R.id.rb_yejian:
                        isNightMode = true;
                        mPageLoader.setNightMode(isNightMode);
                        ll_bg.setBackgroundResource(R.drawable.shape_black);
                        break;
                }*/
                if (checkedId == R.id.rb_rijian) {
                    isNightMode = false;
                    mPageLoader.setNightMode(isNightMode);
                    ll_bg.setBackgroundResource(R.drawable.shape_while);
                } else if (checkedId == R.id.rb_yejian) {
                    isNightMode = true;
                    mPageLoader.setNightMode(isNightMode);
                    ll_bg.setBackgroundResource(R.drawable.shape_black);
                }

                Intent intent = new Intent();
                intent.setAction(ReadActivity.nightMode);
                mActivity.sendBroadcast(intent);
            }
        });
    }


    private void setTabs(TabLayout tabLayout, LayoutInflater inflater, Integer[] tabbg, int pos) {
        List<LinearLayout> list = new ArrayList<>();
        for (int i = 0; i < tabbg.length; i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.readbg_item_tab, null);
            view.setId(i);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            LinearLayout ll_bg = (LinearLayout) view.findViewById(R.id.ll_bg);
            list.add(ll_bg);
            TextView tv_bg = (TextView) view.findViewById(R.id.tv_bg);
            ImageView img_vip = (ImageView) view.findViewById(R.id.img_vip);
            tv_bg.setBackgroundResource(tabbg[i]);
            if (pos == i) {
                ll_bg.setBackgroundResource(R.drawable.read_vip_bg_select);
            } else {
                ll_bg.setBackgroundResource(R.color.transparent);
            }
            // 显示Vip标签
            if (i < UserInfoBg.INSTANCE.getTHEME().length -1) {
                img_vip.setVisibility(View.VISIBLE);
            } else {
                img_vip.setVisibility(View.GONE);
            }
            int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (PreUtils.getBoolean("tourist", true) || StUtils.isEmpty(PreUtils.getString("token", ""))) {
                        if (!isVip && finalI < UserInfoBg.INSTANCE.getTHEME().length - 1) {
                            Intent intent = new Intent(v.getContext(), LoginActivity.class);
                            v.getContext().startActivity(intent);
                            return;
                        }
                    }

//                    if (!isVip && finalI < UserInfoBg.INSTANCE.getTHEME().length) {
                    if (!isVip && finalI < UserInfoBg.INSTANCE.getTHEME().length - 1) {
//                        FFApplication.showToast("當前非VIP");
                        if (dialogShow != null) {
                            dialogShow.show(v);
                        }
                        return;
                    }
                    for (int i = 0; i < tabbg.length; i++) {
                        if (finalI == i) {
                            list.get(i).setBackgroundResource(R.drawable.read_vip_bg_select);
                            mPageLoader.setPageStyle(PageStyle.values()[finalI]);
                            FFApplication.showToast("切换背景成功");
                        } else {
                            list.get(i).setBackgroundResource(R.color.transparent);
                        }

                    }
                }
            });
            tabLayout.addTab(tab);
        }
    }

    public void setIsVip(boolean vip) {
        isVip = vip;
    }

    /**
     * 設置系統亮度是否跟隨
     * @param isStatus
     */
    private void setFollowSystem(boolean isStatus) {
        if (isStatus) {
            BrightnessUtils.setBrightness(mActivity, screenBrightness);
//            mSbBrightness.setProgress(screenBrightness);
            //存儲亮度的進度條
//            ReadSettingManager.getInstance().setBrightness(screenBrightness);

            cb_follow_system.setChecked(true);
            iv_follow_system.setImageResource(R.mipmap.icon_checked_select);
            fl_follow_system.setBackgroundResource(R.drawable.shape_e5efee_radius_50_bg);
        } else {
            //設置當前 Activity 的亮度
            BrightnessUtils.setBrightness(mActivity, mSettingManager.getBrightness());
            //存儲亮度的進度條
//            ReadSettingManager.getInstance().setBrightness(mSettingManager.getBrightness());

            // 跟隨系統變化控件
            cb_follow_system.setChecked(false);
            iv_follow_system.setImageResource(R.mipmap.icon_checked_unselect);
            fl_follow_system.setBackgroundResource(R.drawable.shape_4e4e4e_radius_50_bg);
        }
    }

    public void setVipDialogShow(VIPDialogShow dialogShow) {
        this.dialogShow = dialogShow;
    }

    private VIPDialogShow dialogShow;

    public interface VIPDialogShow {
        public void show(View view);
    }
}
